﻿using NfsCommon;
using NfsCommon.DbHelper;
using NfsModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NfsDAL
{
	/// <summary>
	/// 数据访问类:account
	/// </summary>
	public partial class AccountDAL
	{
		public AccountDAL()
		{}
		#region  Method

		/// <summary>
		/// 得到最大ID
		/// </summary>
		public int GetMaxId()
		{
		return DbHelperMySQL.GetMaxID("id", "t_account"); 
		}

        public int GetIdentityID(string tableName)
        {
            return DbHelperMySQL.GetIdentityID(tableName);

        }
		/// <summary>
		/// 是否存在该记录
		/// </summary>
		public bool Exists(int id)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) from t_account");
			strSql.Append(" where id="+id+" ");
			return DbHelperMySQL.Exists(strSql.ToString());
		}

		/// <summary>
		/// 增加一条数据
		/// </summary>
        public bool Add(NfsModel.account model, out int id)
		{
			StringBuilder strSql=new StringBuilder();
			StringBuilder strSql1=new StringBuilder();
			StringBuilder strSql2=new StringBuilder();
			if (model.user_name != null)
			{
				strSql1.Append("user_name,");
				strSql2.Append("'"+model.user_name+"',");
			}
			if (model.user_pwd != null)
			{
				strSql1.Append("user_pwd,");
				strSql2.Append("'"+model.user_pwd+"',");
			}
			if (model.IsAdmin != null)
			{
				strSql1.Append("IsAdmin,");
				strSql2.Append(""+model.IsAdmin+",");
			}
			if (model.type != null)
			{
				strSql1.Append("type,");
				strSql2.Append(""+model.type+",");
			}
			if (model.mobile != null)
			{
				strSql1.Append("mobile,");
				strSql2.Append("'"+model.mobile+"',");
			}
			if (model.valid != null)
			{
				strSql1.Append("valid,");
				strSql2.Append(""+model.valid+",");
			}
			if (model.time != null)
			{
				strSql1.Append("time,");
				strSql2.Append("'"+model.time+"',");
			}
			strSql.Append("insert into t_account(");
			strSql.Append(strSql1.ToString().Remove(strSql1.Length - 1));
			strSql.Append(")");
			strSql.Append(" values (");
			strSql.Append(strSql2.ToString().Remove(strSql2.Length - 1));
			strSql.Append(")");
			int rows=DbHelperMySQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
            {
                id = GetIdentityID("t_account");
				return true;
			}
			else
            {
                id = -1;
				return false;
			}
		}

		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update( NfsModel.account model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update t_account set ");
			if (model.user_name != null)
			{
				strSql.Append("user_name='"+model.user_name+"',");
			}
			else
			{
				strSql.Append("user_name= null ,");
			}
			if (model.user_pwd != null)
			{
				strSql.Append("user_pwd='"+model.user_pwd+"',");
			}
			if (model.IsAdmin != null)
			{
				strSql.Append("IsAdmin="+model.IsAdmin+",");
			}
			else
			{
				strSql.Append("IsAdmin= null ,");
			}
			if (model.type != null)
			{
				strSql.Append("type="+model.type+",");
			}
			else
			{
				strSql.Append("type= null ,");
			}
			if (model.mobile != null)
			{
				strSql.Append("mobile='"+model.mobile+"',");
			}
			else
			{
				strSql.Append("mobile= null ,");
			}
			if (model.valid != null)
			{
				strSql.Append("valid="+model.valid+",");
			}
			else
			{
				strSql.Append("valid= null ,");
			}
			if (model.time != null)
			{
				strSql.Append("time='"+model.time+"',");
			}
			else
			{
				strSql.Append("time= null ,");
			}
			int n = strSql.ToString().LastIndexOf(",");
			strSql.Remove(n, 1);
			strSql.Append(" where id="+ model.id+"");
			int rowsAffected=DbHelperMySQL.ExecuteSql(strSql.ToString());
			if (rowsAffected > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(int id)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from t_account ");
			strSql.Append(" where id="+id+"" );
			int rowsAffected=DbHelperMySQL.ExecuteSql(strSql.ToString());
			if (rowsAffected > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string idlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from t_account ");
			strSql.Append(" where id in ("+idlist + ")  ");
			int rows=DbHelperMySQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}


		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public  NfsModel.account GetModel(int id)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select  ");
			strSql.Append(" id,user_name,user_pwd,IsAdmin,type,mobile,valid,time ");
			strSql.Append(" from t_account ");
			strSql.Append(" where id="+id+"" );
			 NfsModel.account model=new  NfsModel.account();
			DataSet ds=DbHelperMySQL.Query(strSql.ToString());
			if(ds.Tables[0].Rows.Count>0)
			{
				return DataRowToModel(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}

		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public  NfsModel.account DataRowToModel(DataRow row)
		{
			 NfsModel.account model=new  NfsModel.account();
			if (row != null)
			{
				if(row["id"]!=null && row["id"].ToString()!="")
				{
					model.id=int.Parse(row["id"].ToString());
				}
				if(row["user_name"]!=null)
				{
					model.user_name=row["user_name"].ToString();
				}
				if(row["user_pwd"]!=null)
				{
					model.user_pwd=row["user_pwd"].ToString();
				}
				if(row["IsAdmin"]!=null && row["IsAdmin"].ToString()!="")
				{
					model.IsAdmin=int.Parse(row["IsAdmin"].ToString());
				}
				if(row["type"]!=null && row["type"].ToString()!="")
				{
					model.type=int.Parse(row["type"].ToString());
				}
				if(row["mobile"]!=null)
				{
					model.mobile=row["mobile"].ToString();
				}
				if(row["valid"]!=null && row["valid"].ToString()!="")
				{
					model.valid=int.Parse(row["valid"].ToString());
				}
				if(row["time"]!=null && row["time"].ToString()!="")
				{
					model.time=DateTime.Parse(row["time"].ToString());
				}
			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select id,user_name,user_pwd,IsAdmin,type,mobile,valid,time ");
			strSql.Append(" FROM t_account ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperMySQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM t_account ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
            object obj = DbHelperMySQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.id desc");
			}
			strSql.Append(")AS Row, T.*  from t_account T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperMySQL.Query(strSql.ToString());
		}

		/*
		*/

		#endregion  Method
		#region  MethodEx
        #region 登录
        public account GetLogin(string userName, string userPwd)
        {
            string strSql = string.Format(@"SELECT * FROM t_account WHERE user_name='{0}' AND user_pwd='{1}' AND valid=1", userName, userPwd);
            DataSet ds = DbHelperMySQL.Query(strSql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }
        #endregion
        #region 修改密码
        public bool UptPassword(int id, string Pwd)
        {
            string strSql = string.Format(@"UPDATE t_account SET user_pwd='{0}' WHERE id={1}", Pwd, id);
            int row = DbHelperMySQL.ExecuteSql(strSql);
            if (row > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 查询修改密码时输入的旧密码是否与数据库的相匹配
        public bool GetPassword(int id, string pwd)
        {
            string strSql = string.Format(@"select count(*) from t_account where id={0} and  user_pwd={1} ", id, pwd);
            int row = int.Parse(DbHelperMySQL.GetSingle(strSql).ToString());
            if (row > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion
        #region PC模糊查询
        public DataTable GetAccountBycondtion(int pageindex, int pagesize, string Name,string mobile,int type)
        {
            int startindex = (pageindex - 1) * pagesize;
            string strSql = @"select top "+pagesize+"* from (select row_number() over(order by id desc) as rownumber,id,user_name,user_pwd,IsAdmin,type,mobile,valid,time,case when IsAdmin=1 then '管理员' else '普通用户' end  as IsAdminName,case when type=1 then '所有权限' else '查看权限' end as TypeName  from t_account where  valid=1  and IsAdmin=1 {0}";
            string tem = string.Empty;
            if (type ==2)
            {
                tem += " and type=2";
            }
            if (Name != null && Name != "")
            {
                tem += " and user_name like '%" + Name + "%'";
            }
            if (mobile != null && mobile != "")
            {
                tem += " and mobile like '%" + mobile + "%'";
            }
            strSql = string.Format(strSql,tem);
            strSql += ") as b where b.rownumber>" + startindex+" ";
            return DbHelperMySQL.Query(strSql).Tables[0];
        }
        public object GetAccountBycondtionCount(string Name,string mobile)
        {
            string strSql = string.Format(@"select count(*) from t_account where  valid=1  and IsAdmin=1");
            if (Name != null && Name != "")
            {
                strSql += " and user_name like '%" + Name + "%'";
            }
            if (mobile != null && mobile != "")
            {
                strSql += " and mobile like '%" + mobile + "%'";
            }
            
            return DbHelperMySQL.GetSingle(strSql);
        }
        #endregion
		#endregion  MethodEx

        #region 删除(逻辑删除)全局共用
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="tabName">表名</param>
        /// <param name="name">字段</param>
        /// <param name="valid">值</param>
        /// <returns></returns>
        public bool com_delelte(int id,string tabName,string name,int valid)
        {

            string strSql = string.Format(@"UPDATE {0}  SET {1}={2} WHERE id={3}", tabName,name,valid,id);
            int row = DbHelperMySQL.ExecuteSql(strSql);
            if (row > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        
        
        }

        #endregion
    }
}

